#include <SoftwareSerial.h>

 /*  This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
 */
 

/*
Serial Bridge - 
 This sketch acts as a bridge between Serial comms received in pins 10 & 11 and the 
 USB (Rx, TX) Serial ports. 
 
 This was initially created as the Android drivers for connecting an APC220 wireless module 
 were not available
 */
 

SoftwareSerial softSerial(10, 11); // RX, TX

//Status Pins
const int powerIndPin = 4;
const int commsIndPin = 8;

//comms indicator variables
bool didReceiveFirstByte = false;
volatile unsigned long lastByteTime = 0;
const int commsThresholdTime = 1500; //in milliseconds. Comms must be received within this interval for indicator to stay on

void setup()  
{
  Serial.begin(9600); //USB Serial baud rate

  // set the data rate for the SoftwareSerial port
  softSerial.begin(9600);

  //initialise status pins
  pinMode(powerIndPin, OUTPUT);
  pinMode(commsIndPin, OUTPUT);

  digitalWrite(powerIndPin, HIGH);
  digitalWrite(commsIndPin, LOW);


}

void loop() // run over and over
{
  //read from softSerial and Write to usb serial
  if (softSerial.available()){
    Serial.write(softSerial.read());
    if (!didReceiveFirstByte)
      didReceiveFirstByte = true;
    lastByteTime = millis();     
  }

  //should the comms indicator be on?
  if (didReceiveFirstByte && ((lastByteTime + commsThresholdTime) > millis()))
    digitalWrite(commsIndPin, HIGH);
  else
    digitalWrite(commsIndPin, LOW);


  //read from USB Serial and write to softSerial
  if (Serial.available())
    softSerial.write(Serial.read());
}




